package com.syl.auth.utils;

import com.syl.auth.config.SmallSecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @Author YunLong
 * @Date 2023/4/27 22:41
 * @Description SecurityUtil
 **/
@Component
public class SecurityUtil {

    @Resource
    SmallSecurityProperties smallSecurityProperties;

    static String secret;
    static Long expiration;
    public static String authenticationFailedCode;
    public static String permissionDeniedCode;
    public static String unauthorizedCode;

    @PostConstruct
    public void init() {
        secret = smallSecurityProperties.getJwtSecret();
        expiration = smallSecurityProperties.getExpiration();
        authenticationFailedCode = smallSecurityProperties.getAuthenticationFailedCode();
        permissionDeniedCode = smallSecurityProperties.getPermissionDeniedCode();
        unauthorizedCode = smallSecurityProperties.getUnauthorizedCode();
    }

    /**
     * @Author YunLong
     * @Date 2023/4/27 22:43
     * @Description 生成token
     **/
    public static String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(createExpirationDate())
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    /**
     * @Author YunLong
     * @Date 2023/4/27 22:44
     * @Description 增加主题生成token
     **/
    public String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setExpiration(createExpirationDate())
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    /**
     * @Author YunLong
     * @Date 2023/4/27 22:44
     * @Description 获取token中的信息 Claims
     **/
    public static Claims getClaims(String token) throws Exception {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * @Author YunLong
     * @Date 2023/4/27 22:45
     * @Description 过期时间
     **/
    private static Date createExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

}
